package me.dongcha.reggie402.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import me.dongcha.reggie402.common.R;
import me.dongcha.reggie402.entity.Category;
import me.dongcha.reggie402.entity.Dish;
import me.dongcha.reggie402.entity.DishDto;
import me.dongcha.reggie402.entity.DishFlavor;
import me.dongcha.reggie402.service.CategoryService;
import me.dongcha.reggie402.service.DishFlavorService;
import me.dongcha.reggie402.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishdto) {
        log.warn("dishdto里面包含菜品基本信息和菜品口味列表信息:{}", dishdto);
        dishService.saveWithFlavor(dishdto);

        String key = "dish_" + dishdto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);

        dishService.page(pageInfo, wrapper);

        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        List<DishDto> records = new ArrayList<>();
        List<Dish> pageInfoRecords = pageInfo.getRecords();
        for (Dish dish : pageInfoRecords) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long categoruId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoruId);
            dishDto.setCategoryName(category.getName());
            records.add(dishDto);
        }
        dishDtoPage.setRecords(records);

        return R.success(dishDtoPage);
    }

    @GetMapping("/{id}")
    public R<DishDto> echo(@PathVariable Long id) {
        log.warn("[要查询的id]:" + id);
        DishDto dishDto = dishService.getByIdWithFlovor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        log.warn("[修改前的基本数据和口味关联数据]:" + dishDto);
        log.warn("[修改后的基本数据和口味关联数据]:" + dishDto);
        dishService.updateByIdWithFlavor(dishDto);

        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    @PostMapping("/status/{sta}")
    @Transactional
    public R<String> updateStatusByIds(@PathVariable Integer sta, Long[] ids) {
        for (Long id : ids) {
            LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Dish::getStatus, sta);
            wrapper.eq(Dish::getId, id);
            dishService.update(wrapper);
        }
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("批量修改状态成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Long categoryId, Integer status) {
        String key = "dish_" + categoryId;
        List<DishDto> redisDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (redisDtoList != null) {
            log.warn("[取数据的地方]:redis");
            return R.success(redisDtoList);
        }

        log.warn("[需要查询的菜品分类id]:" + categoryId);
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        wrapper.eq(status != null, Dish::getStatus, status);

        List<Dish> dishList = dishService.list(wrapper);

        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dish : dishList) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Long dishId = dishDto.getId();
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlavorService.list(wrapper1);
            dishDto.setFlavors(flavors);
            dishDtoList.add(dishDto);
        }

        redisTemplate.opsForValue().set(key, dishDtoList);

        log.warn("[取数据的地方]:MySQL");

        return R.success(dishDtoList);
    }
}
